package com.github.raffle.thread;

import java.util.concurrent.BlockingQueue;

/**
 * @author Stephen Liu
 * @version 1.0.0
 * @since 2017/5/8
 */
public class PoolThread extends Thread {
    private BlockingQueue<Runnable> taskQueue;
    private boolean isStopped = false;

    public PoolThread(BlockingQueue<Runnable> taskQueue) {
        this.taskQueue = taskQueue;
    }

    @Override
    public void run() {
        while(!isStopped()){
            try{
                Runnable runnable = taskQueue.take();
                runnable.run();
            } catch(Exception e){
                //log or otherwise report exception,
                //but keep pool thread alive.
            }
        }
    }

    public synchronized void doStop(){
        isStopped = true;
        this.interrupt(); //break pool thread out of dequeue() call.
    }

    public synchronized boolean isStopped(){
        return isStopped;
    }
}
